package cn.wizzer.app.web.modules.controllers.open;

import cn.wizzer.app.sys.modules.models.SysParam;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.models.constant.RedisKey;
import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.app.web.commons.utils.TokenUtil;
import cn.wizzer.framework.util.Id;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.util.param.ParamVerify;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.dao.Cnd;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

@IocBean
@At("/open/email")
public class ApiEmailController {
    @Inject
    private RedisService redisService;

    @Inject
    private TokenUtil tokenUtil;

    @Inject
    @Reference
    private SysParamService sysParamService;
    @Inject
    @Reference
    private UserService userService;

    @At
    @Ok("json")
    @ULog(tag = "发送邮箱验证码", msg = "邮箱: ${email}, 操作: ${type}")
    public Result sendCode(@ParamVerify(required = true, name = "email") String email,
                           @ParamVerify(required = true, name = "type") String type) {
        int num = userService.count(Cnd.where("email", "=", Strings.trim(email)));
        String appid = Mvcs.getReq().getHeader("appid");
        if ("update".equals(type) && num > 0) {
            return Result.error(BizExceptionEnum.EMAIL_REGISTERED);
        } else if ("resetPassword".equals(type) && num == 0) {
            return Result.error(BizExceptionEnum.EMAIL_UNREGISTERED);
        } else if ("safe".equals(type)) {
            if (!tokenUtil.verifyToken(appid, Mvcs.getReq().getHeader("token"))) {
                return Result.error(BizExceptionEnum.UN_LOGIN);
            }
            String userEmail = userService.fetch(appid).getEmail();
            if (!userEmail.equals(email)) {
                return Result.error(BizExceptionEnum.ERROR_EMAIL);
            }
        }

        String key = "code#email#" + type + ":" + email;
        // 该邮箱是否在一分钟内已获取过短信验证码
        String value = redisService.get(key);
        if (value != null && redisService.ttl(key) > 240) {
            return Result.error(BizExceptionEnum.DO_NOT_GET_CODES_FREQUENTLY);
        }
        // 全局参数取标题、内容。拼接邮箱验证码
        SysParam sysParam = sysParamService.fetch();
        // 生成邮箱验证码
        String emailCode = Id.createVerifyCode();
        // 邮件内容
        String content = String.format(sysParam.getEmailContent(), emailCode);
        // 发送邮箱验证码
        sysParamService.sendEmail(email, sysParam.getEmailTitle(), content);
        // 加入redis中用以查询验证
        redisService.setex(key, RedisKey.M_5, emailCode);
        return Result.success(BizExceptionEnum.SEND_CODE_SUCCESS);
    }
}
